package com.example.security;

import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * Spring Security 配置类
 */
@EnableMethodSecurity(securedEnabled = true) //开启方法权限控制
@RequiredArgsConstructor
@Configuration
public class SecurityConfig {

    private final LoginUnAuthenticationEntryPointHandler loginUnAuthenticationEntryPointHandler;
    private final JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;
    private final LogoutStatusSuccessHandler logoutStatusSuccessHandler;
    private final LoginUnAccessDeniedHandler loginUnAccessDeniedHandler;
    /**
     * Spring Security 过滤器
     */
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http.csrf().disable() //防止跨站请求伪造
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) //取消session
                .and()
                .authorizeRequests()
                .antMatchers("/login", "/test1").permitAll() //登陆和未登录的人都可以访问访问
                .anyRequest().authenticated();//除了上面设置的地址可以匿名访问,其它所有的请求地址需要认证访问
        //将自定义的过滤器注册到SpringSecurity过滤器链中,并且设置到UsernamePasswordAuthenticationFilter前面
        http.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
        //注册匿名访问私有资源的处理器(未认证用户访问需要认证资源的处理器)
        http.exceptionHandling().authenticationEntryPoint(loginUnAuthenticationEntryPointHandler);
        //注册退出处理器
        http.logout().logoutSuccessHandler(logoutStatusSuccessHandler);
        //注册权限不足处理器
        http.exceptionHandling().accessDeniedHandler(loginUnAccessDeniedHandler);
        return http.build();
    }

    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    /**
     * 配置认证管理器
     */
    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception {
        return authenticationConfiguration.getAuthenticationManager();
    }



}
